package com.groupbuying.generator.service.impl;

import com.groupbuying.generator.dao.GeneratorDao;
import com.groupbuying.generator.utils.SqlInjectionReg;
import com.groupbuying.generator.service.GeneratorService;
import com.groupbuying.generator.utils.GenUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;


@Service
public class GeneratorServiceImpl implements GeneratorService {
    @Autowired
    GeneratorDao generatorDao;

    @Override
    public List<Map<String, String>> doSearch(Map<String, Object> map){
        String tableName = map.get("tableName").toString();
        List<Map<String, String>> list = generatorDao.get(tableName);
        return list;
    }


    @Override
    public List<Map<String, Object>> list(Map<String, Object> map) {
        List<Map<String, Object>> list = generatorDao.list(map);
        return list;
    }

    @Override
    public int count() {
        return generatorDao.count();
    }

    @Override
    public byte[] generatorCode(String[] tableNames, String name, String packageName, String email) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {

            //检测tableName是否通过防SQL注入检测
            if (!SqlInjectionReg.isValid(tableName)) {
                break;
            }
            //查询表信息
            List<Map<String, String>>  table = generatorDao.get(tableName);
            //查询列信息
            List<Map<String, String>> columns = generatorDao.listColumns(tableName);
            //生成代码
            GenUtils.generatorCode(table.get(0), columns, zip, name, packageName, email);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

}
